package cn.duckerkj.localsynchronize;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Foo {
	//可重入的读写锁
		private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
		//读锁
		private final Lock rLock = readWriteLock.readLock();
		//写锁
		private final Lock wLock = readWriteLock.writeLock();	
		
		int i=0;
		
		//多操作 可并发执行
		public void read() {
			try {
				rLock.lock();
				TimeUnit.MILLISECONDS.sleep(1000);
				System.out.println(Thread.currentThread().getName()+"read......."+i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				// TODO: handle finally clause
				rLock.unlock();
			}
		}
		//写操作 同时只允许一个写操作
		public void write() {
			try {
				wLock.lock();
				TimeUnit.MILLISECONDS.sleep(1000);
				i++;
				System.out.println(Thread.currentThread().getName()+"write......."+i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				// TODO: handle finally clause
				wLock.unlock();
			}
		}
}
